import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_list_view/flutter_list_view.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/food/food_menu_list.dart';
import 'package:ls_work/ui/food/apply_select_food_page.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:sticky_headers/sticky_headers/widget.dart';

import '../../net/api/http_api.dart';
import '../../net/response/food/site_list_data.dart';
import '../../res/colors.dart';
import '../../util/image_utils.dart';

class SingleFoodMenuViewModel extends BaseListViewModel<FoodData> {
  final String? date;
  final SiteListData? site;
  final String? orderType;
  final PickerDataWithIdModel? foodTime;
  final int? useNumber;
  final PickerDataWithIdModel? userWay;

  SingleFoodMenuViewModel(BuildContext context,
      {this.date, this.orderType, this.site, this.foodTime, this.useNumber,this.userWay})
      : super(context);

  FoodData? selectedType;

  @override
  Future<List<FoodData>> requestListData() async {
    var map = await PostRequest.foodMenuList(site?.id.toString()??"",
        date?.changeTime(format: [yyyy, '-', mm, '-', dd])??"", foodTime?.pickId.toString()??"",orderType??"");
    if ('0' == map['code'].toString()) {
      var list =
          ((map['data'] as List?)??[]).map((e) => FoodMenuList.fromJson(e)).toList();
      var foodDataList = <FoodData>[];
      for (var item in list) {
        var data = FoodData(typeName: item.typeName??"");
        if (foodDataList.contains(data)) {
          var index = foodDataList.indexOf(data);
          (foodDataList[index].foodMenu??[]).add(item);
        } else {
          data.foodMenu = [item];
          foodDataList.add(data);
        }
      }
      if (foodDataList.isNotEmpty) {
        selectedType = foodDataList[0];
      }
      return foodDataList;
    } else {
      throw map['msg'];
    }
  }

  Widget menuTypeWidget() {
    return FlutterListView.builder(
      itemBuilder: (context, index) {
        var item = listItems[index];
        var count = item.selectCount;
        return Stack(
          alignment: Alignment.center,
          fit: StackFit.expand,
          children: [
            CommonText(item.typeName)
                .addToContainer(alignment: Alignment.center),
            count == 0
                ? Container()
                : CommonText(count.toString(),
                        textColor: Colors.white, textSize: 14)
                    .addToContainer(
                        decoration: BoxDecoration(
                            shape: BoxShape.circle, color: Colors.red),
                        width: 16,
                        height: 16,
                        alignment: Alignment.center)
                    .setLocation(right: 0, top: 4)
          ],
        )
            .addToContainer(
          width: double.infinity,
          height: 50,
          color: selectedType == item ? Colors.white : Colors.transparent,
          alignment: Alignment.center,
        )
            .onTap(() {
          selectedType = item;
          notifyListeners();
          jumpTo(index);
        });
      },
      itemCount: listItems.length,
    );
  }

  void jumpTo(int index) {
    double offset = 0;
    if (index == 0) {
      menuController.jumpTo(0);
    }
    for (var i = 0; i < index; i++) {
      offset += (listItems[i].foodMenu??[]).length * 90.0 + 40;
    }
    menuController.jumpTo(offset);
  }

  ///菜单content
  Widget foodMenuWidget() {
    return ListView.builder(
      controller: menuController,
      cacheExtent: 1,
      itemBuilder: (context, index) {
        var item = listItems[index];
        return StickyHeader(
            header: CommonText(item.typeName).addToContainer(
                color: Colors.white,
                width: double.infinity,
                height: 40,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(
                  horizontal: 10,
                )),
            content: ListView(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              children: item.foodMenuList.map((e) {
                return Stack(
                  children: [
                    (e.imgAttachId == null
                        ? ImageLoad(
                      ImageUtils.getImgPath('none'),
                      width: 70,
                      height: 70,
                      isAsset: true,
                    )
                        : ImageLoad(
                      '${HttpApi.imageHead}${e.imgAttachId}',
                      width: 70,
                      height: 70,
                      fit: BoxFit.cover,
                    )).toRound(borderRadius: 4.borderRadius),
                    Column(
                      children: [
                        CommonText(e.foodShowName),
                        Container(),
                      ],
                    ).setLocation(left: 80, top: 5),
                    CommonText('¥${e.price}',
                            textSize: 14, textColor: Colors.red)
                        .setLocation(left: 80, bottom: 0),
                    Row(
                      children: [
                        e.selectNum == 0
                            ? Container()
                            : Icon(
                                Icons.remove_circle_outline,
                                color: Colours.app_main,
                              ).onTap(() {
                                if (e.selectNum <= 0) {
                                  return;
                                }
                                e.selectNum--;
                                notifyListeners();
                              }),
                        e.selectNum == 0
                            ? Container()
                            : CommonText(e.selectNum.toString()).addToContainer(
                                margin: EdgeInsets.symmetric(horizontal: 14)),
                        Icon(
                          Icons.add_circle_outline_rounded,
                          color: Colours.app_main,
                        ).onTap(() {
                          e.selectNum++;
                          notifyListeners();
                        }),
                      ],
                    ).setLocation(right: 0, bottom: 0)
                  ],
                ).addToContainer(
                    color: Colors.white,
                    height: 90,
                    padding:
                        EdgeInsets.symmetric(horizontal: 10, vertical: 10));
              }).toList(),
            ));
      },
      itemCount: listItems.length,
    );
  }

  Widget bottomWidget() {
    var totalPrice = getTotalPrice();
    return Row(
      children: [
        Container(
          width: 16,
        ),
        CommonText('价格：', textSize: 16, fontWeight: FontWeight.bold),
        CommonText('¥$totalPrice',
            textColor: Colors.red, textSize: 17, fontWeight: FontWeight.bold),
        Container().setWeight(1),
        TextButton(
          onPressed: () {
            var goods = getSelectFood();
            if (goods.isEmpty) {
              showToast('请先选择菜品');
              return;
            }
            Go().push(ApplySelectFoodPage(
                date: date!,
                site: site!,
                orderType: orderType!,
                foodTime: foodTime!,
                useNumber: useNumber!,
                selectFood: goods,
                totalPrice: totalPrice,userWay: userWay!,));
          },
          child: CommonText(
            '去下单',
            textColor: Colors.white,
          ),
          style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(Colours.app_main),
              shape: WidgetStateProperty.all(RoundedRectangleBorder()),
              minimumSize:
                  WidgetStateProperty.all(Size(140, double.infinity))),
        )
      ],
    ).addToContainer(height: 60, color: Colors.white);
  }

  num getTotalPrice() {
    num price = 0;
    for (var item in listItems) {
      price += item.selectPrice;
    }
    return price;
  }

  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
    _addListener();
  }

  FlutterListViewController menuController = FlutterListViewController();

  void _addListener() {
    menuController.addListener(() {
      var index = menuController.offset;
    });
  }

  List<FoodMenuList> getSelectFood() {
    var list = <FoodMenuList>[];
    for (var item in listItems) {
      list.addAll(item.selectFoodList);
    }
    return list;
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.PAY_FOOD_SUCCESS){
      requestRefresh();
    }
  }
}

class FoodData extends SingleFoodMenuData {
  String? typeName;
  List<FoodMenuList>? foodMenu;

  FoodData({this.typeName, this.foodMenu});

  @override
  List<FoodMenuList> get foodMenuList => foodMenu??[];

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is FoodData &&
          runtimeType == other.runtimeType &&
          typeName == other.typeName;

  @override
  int get hashCode => typeName.hashCode;

  @override
  List<FoodMenuList> get selectFoodList {
    List<FoodMenuList> items = [];
    for (var item in (foodMenu??<FoodMenuList>[])) {
      if (item.selectNum > 0) {
        items.add(item);
      }
    }
    return items;
  }

  num get selectCount {
    num count = 0;
    for (var item in selectFoodList) {
      count += (item.selectNum??0);
    }
    return count;
  }

  num get selectPrice {
    num price = 0;
    for (var item in selectFoodList) {
      price += (item.price??0) * item.selectNum;
    }
    return price;
  }
}

abstract class SingleFoodMenuData {
  List<SingleFoodMenuListData> get foodMenuList;

  List<SingleFoodMenuListData> get selectFoodList;
}

abstract class SingleFoodMenuListData {
  num selectNum = 0;

  String get foodShowName;

  num get showFoodPrice;
}
